package com.example.shardingsphere.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.shardingsphere.entity.Order;
import com.example.shardingsphere.entity.OrderItem;
import com.example.shardingsphere.mapper.OrderItemMapper;
import com.example.shardingsphere.mapper.OrderMapper;
import com.example.shardingsphere.service.OrderService;
import org.apache.shardingsphere.api.hint.HintManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public Integer saveOrder(Order order) {
        return orderMapper.save(order);
    }

    @Override
    public Integer saveOrderItem(OrderItem orderItem, Integer userId) {
        try (HintManager hintManager = HintManager.getInstance()) {
            hintManager.addDatabaseShardingValue("t_order_item", userId);
            return orderItemMapper.save(orderItem);
        }
    }

    @Override
    public Order selectBySharding(Integer userId, Integer orderId) {
        return orderMapper.selectBySharding(userId, orderId);
    }

    @Override
    public Order selectBySharding2(Integer userId, Integer orderId) {
        try (HintManager hintManager = HintManager.getInstance()) {
            hintManager.addTableShardingValue("t_order", userId);
            hintManager.addTableShardingValue("t_order", orderId);
            return orderMapper.selectBySharding(userId, orderId);
        }
    }

    @Override
    public List<Order> selectByRangeSharding(Integer userId, Integer oidStart, Integer oidEnd) {
        return orderMapper.selectByRangeSharding(userId, oidStart, oidEnd);
    }

}
